package com.sample.thread.toilet;

import com.sample.thread.util.JsonUtils;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * <p>Description: </p>
 * 场景：公司有若干部门，每个部门一个厕所，每个部门的员工争抢本部门的厕所
 * @author zg
 * @version v1.0.0
 * @since 2024/8/22
 **/
public class ToiletTester {

    //部门数量
    private static final int deptNum = 3;
    //总人数
    private static final int personNum = 10;
    //所有部门的厕所
    public static Map<Integer, Toilet> DepToilets = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        //初始化厕所
        for (int i = 1; i <= deptNum; i++) {
            DepToilets.put(i, new Toilet(i));
        }
        List<Person> persons = new ArrayList<>();
        //把员工随机分配到各个（从1到5）
        for (int i = 1; i <= personNum; i++) {
            int depId = new SplittableRandom().nextInt(1, deptNum+1);
            String empName = fixedLengthFill0(3, i) + "号";
            persons.add(new Person(depId, empName));
        }
        Map<Integer, List<Person>> deptPersons = persons.stream().collect(Collectors.groupingBy(Person::getDepId));
        for (Map.Entry<Integer, List<Person>>  entrySet : deptPersons.entrySet()){
            List<Person> personList = entrySet.getValue();
            List<String> nameList = personList.stream().map(Person::getName).collect(Collectors.toList());
            System.out.println("部门"+entrySet.getKey()+"员工：\n" + JsonUtils.toJsonString(nameList));
        }

        //去厕所
        for (Person person : persons) {
            person.start();
        }

    }

    //------------- 工具方法  ------------------------------
    private static String fixedLengthFill0(int length, int seq) {
        StringBuilder strBu = new StringBuilder();
        int fillLen = length - String.valueOf(seq).length();
        for (int i = 0; i < fillLen; i++) {
            strBu.append("0");
        }
        strBu.append(seq);
        return strBu.toString();
    }

}
